<script lang="ts" setup>

import {onMounted, reactive, ref, UnwrapRef} from 'vue';
import {message, type UploadChangeParam} from "ant-design-vue";
import {pageOfferAPI, updateOfferAPI} from "@/apis/offer.ts";
import {useInfoStore} from "@/store/user/user.ts";
import dayjs, {type Dayjs} from "dayjs";
import type {Rule} from "ant-design-vue/es/form";
import {InboxOutlined} from "@ant-design/icons-vue";
import {addReportAPI} from "@/apis/report.ts";
//中间岗列表
const data = <any>reactive([]);
const userStore = useInfoStore().userInfo;
const getOfferList = async () => {
  const res = await pageOfferAPI({
    pageCurrent: pagination.value.current,
    pageSize: pagination.value.pageSize,
    offerEmployerId: userStore.userId,//招聘者id
  });
  if (res.data.flag) {
    pagination.value.total = res.data.data.total
    data.push(...res.data.data.data)
  } else {
    message.error(res.data.message)
  }
}
//生命周期
onMounted(() => {
  getOfferList();
})

const columns = [
  //头像
  {
    title: '头像',
    dataIndex: 'userAvatarUrl',
    key: 'userAvatarUrl',
  },
  {
    title: '兼职名称',
    dataIndex: 'jobTitle',
    key: 'jobTitle',
  },
  {
    title: '求职姓名',
    dataIndex: 'resumeUsername',
    key: 'resumeUsername',
  },
  {
    title: 'offer状态',
    dataIndex: 'offerStatus',
    key: 'offerStatus',
  },
  {
    title: '截止时间',
    dataIndex: 'offerEndTime',
    key: 'offerEndTime',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
  },
];

// 分页配置
const pagination = ref({
  current: 1, // 当前页码，初始为第 1 页
  pageSize: 8, // 每页显示的记录数
  total: 0, // 数据总条数
});

// 处理表格变化（如分页、排序、筛选）的回调函数
const handleTableChange = (paginationInfo: any) => {
  console.log(paginationInfo)
  pagination.value.current = paginationInfo.current;
  pagination.value.pageSize = paginationInfo.pageSize;
  getOfferList();
};
//编辑
const updateOffer = (record: any) => {
  open.value = true;
  formState.offerId = record.offerId
  formState.jobTitle = record.jobTitle
  formState.resumeUsername = record.resumeUsername
  formState.offerEndTime = dayjs(record.offerEndTime)
  formState.offerRemarks = record.offerRemarks
};
//通过-发出Offer
const open = ref<boolean>(false);
const handleOk = (formState: any) => {
  updateOfferAPI(formState).then((res) => {
    if (res.data.flag) {
      message.success(res.data.message)
      open.value = false
      data.splice(0, data.length)
      getOfferList();
    } else {
      message.error(res.data.message)
    }
  })
};

//表单数据
interface FormState {
  offerId: string
  resumeUsername: string
  jobTitle: string
  offerEndTime: Dayjs | null | string
  offerRemarks: string
}

const formState: UnwrapRef<FormState> = reactive({
  offerId: '',
  resumeUsername: '',
  jobTitle: '',
  offerEndTime: null,
  offerRemarks: '',

});

const rules: Record<string, Rule[]> = {
  offerEndTime: [
    {required: true, message: '请选择截止时间', trigger: 'change'},
  ],
  resumeUsername: [
    {required: true, message: '请选择截止时间', trigger: 'change'},
  ],
  jobTitle: [
    {required: true, message: '请选择截止时间', trigger: 'change'},
  ],
  offerRemarks: [
    {required: true, message: '请补充备注信息', trigger: 'change'},
  ],
};

//举报弹窗
const labelCol = {span: 5};
const wrapperCol = {span: 13};
const openReport = ref<boolean>(false);

const showModalVerification = (record: any) => {
  openReport.value = true;
  formState.offerId = record.offerId
};

const handleOkVerification = () => {
  formRefReport.value
      .validate()
      .then(async () => {
        openReport.value = false;
        //循环加入文件url
        formStateReport.reportFileList = fileListReport.value.map((file: any) => {
          return file.response.data;
        });
        addReportAPI({
          reportCheckStatus: '审核中',
          reportUserId: userStore.userId,
          reportUserRole: 'employer',
          reportUsername: userStore.userName,
          reportAccount: userStore.account,
          reportContact: formStateReport.reportContact,//举报人联系方式
          reportObjectId: formState.offerId, //被举报对象id
          reportObject: formStateReport.reportObject,
          reportDescribe: formStateReport.reportDescribe,
          reportFileList: formStateReport.reportFileList,//上传的文件列表
        }).then((res: any) => {
          if (res.data.flag) {
            message.success('提交成功');
          } else {
            message.error('提交失败');
          }
        })
      })
      .catch(() => {
        console.log("验证失败");
      });
};

interface FormStateReport {
  reportFileList: string[];
  reportDescribe: string;
  reportObject: string;
  reportContact: string;
}

const formRefReport = ref();
const rules1: Record<string, Rule[]> = {
  reportObject: [
    {required: true, message: '请选择举报类型', trigger: 'blur',},
  ],
  reportContact: [
    {required: true, message: '请输入联系方式', trigger: 'blur',},
  ],
  reportDescribe: [
    {required: true, message: '请输入举报描述', trigger: 'blur',},
  ],
}
const formStateReport = reactive<FormStateReport>({
  reportFileList: [], //上传的文件列表
  reportDescribe: '',
  reportObject: '投诉求职者',
  reportContact: '',
})

const fileListReport = ref([]);
const handleChangeReport = (info: UploadChangeParam) => {
  const status = info.file.status;
  if (status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (status === 'done') {
    message.success(`${info.file.name} file uploaded successfully.`);
    console.log("url:" + fileListReport.value[0].response.data);
  } else if (status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};

function handleRemove(e: DragEvent) {
  console.log('删除了', e.response.data);
}
</script>

<template>

  <a-modal v-model:open="open" :title="'发出-'+formState.resumeUsername+'的Offer！'" cancelText="取消"
           okText="确认" @ok="handleOk(formState)">
    <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
    >
      <div style="
              border: 1px solid #4D7181;
              border-radius: 20px;
              display: flex;
              align-items: center;
              justify-items: center;
              flex-direction: column;">
        <a-divider orientation="center" style="color:#4D7181; font-size: 20px">Offer-信息</a-divider>
        <a-form-item ref="resumeUsername" label="Offer-姓名" name="resumeUsername">
          <a-input v-model:value="formState.resumeUsername" :disabled="true"
                   style="width: 350px;"/>
        </a-form-item>
        <a-form-item ref="jobTitle" label="Offer-岗位" name="jobTitle">
          <a-input v-model:value="formState.jobTitle" :disabled="true"
                   style="width: 350px;"/>
        </a-form-item>
        <a-form-item ref="offerEndTime" label="截止-时间" name="offerEndTime">
          <a-date-picker v-model:value="formState.offerEndTime"
                         show-time
                         style="width: 350px;"/>
        </a-form-item>
        <a-form-item ref="offerRemarks" label="补充-信息"
                     name="offerRemarks">
          <a-textarea v-model:value="formState.offerRemarks"
                      :auto-size="{minRows: 4, maxRows: 10}"
                      :maxlength="300"
                      show-count
                      style="width: 350px"
          />
        </a-form-item>
      </div>
    </a-form>
  </a-modal>
  <div class="title">
    <h1>Offer 列 表</h1>
  </div>
  <div class="content_table">
    <a-table :columns="columns" :data-source="data" :pagination="pagination" @change="handleTableChange">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'userAvatarUrl'">
          <img :src="'http://localhost:8080/image/download?name='+record.userAvatarUrl" alt="Avatar"
               style="width: 50px; height: 50px; border-radius: 50%;"/>
        </template>
        <template v-if="column.dataIndex === 'offerEndTime'">
          <p>{{ dayjs(record.offerEndTime).format('YYYY-MM-DD HH:mm:ss') }}</p>
        </template>
        <template v-if="column.dataIndex === 'operation'" >
          <a-button ghost type="primary" v-if="record.offerStatus === '待接受'" style="margin-right: 10px" @click="updateOffer(record)">编辑</a-button>
          <a-button ghost  style="color: white;background-color: #67C23A;margin-right: 10px" v-else @click="updateOffer(record)">查看</a-button>
<!--          <a-button danger ghost type="primary" v-if="record.offerStatus !== '待接受'" style="margin-right: 10px" @click="updateOffer(record.offerId)">删除</a-button>-->
          <a-button danger type="primary" v-if="record.offerStatus === '已接受'" @click="showModalVerification(record)">举报</a-button>
        </template>
      </template>
    </a-table>
  </div>

  <!--          举报弹窗-->
  <div>
    <a-modal v-model:open="openReport"
             cancel-text="取消-举报"
             ok-text="确认-提交举报"
             title="举报-投诉"
             @ok="handleOkVerification">
      <div style="width: 400px;">
        <a-form
            ref="formRefReport"
            :label-col="labelCol"
            :model="formStateReport"
            :rules="rules1"
            :wrapper-col="wrapperCol"
        >
          <a-form-item label="举报要求">
                    <span
                        style="display: block;width: 400px"
                    >
                      要求真实，并且上传相关举报的图片，文字，视频佐证材料等。
                    </span>
          </a-form-item>
          <a-form-item ref="reportObject"
                       label="投诉类型"
                       name="reportObject"
          >
            <a-input v-model:value="formStateReport.reportObject" :disabled="true"/>
          </a-form-item>
          <a-form-item ref="reportContact" label="联系电话" name="reportContact">
            <a-input v-model:value="formStateReport.reportContact"/>
          </a-form-item>
          <a-form-item label="举报描述" name="reportDescribe">
            <a-textarea v-model:value="formStateReport.reportDescribe"
                        :auto-size="{minRows: 2, maxRows: 10}"
                        :maxlength="300"
                        show-count
                        style="width: 300px"/>
          </a-form-item>
          <a-form-item label="佐证材料" name="reportFileList">
            <a-upload-dragger
                v-model:fileList="fileListReport"
                :multiple="true"
                action="http://localhost:8080/file/upload"
                name="file"
                style="width: 400px"
                @change="handleChangeReport"
                @remove="handleRemove"
            >
              <p class="ant-upload-drag-icon">
                <inbox-outlined></inbox-outlined>
              </p>
              <p class="ant-upload-text">单击或拖动文件到此区域上传</p>
              <p class="ant-upload-hint">
                支持单次或批量上传!
              </p>
            </a-upload-dragger>


          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<style scoped>

</style>
